package thread;

import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * Distriptor 的计时器任务
 * @author King
 *
 */
public abstract class DistriptorTimerTask implements ITimerTask
{
	/** 间隔触发的毫秒数 */
	protected long intervalMill;

	/** 执行次数,负数为无限次执行 */
	private int count = -1;
	
	private ScheduledFuture<?> future;
	
	/**派发线程池**/
	private DisruptorSingleProcessor disruptorThread;
	/**是否执行完了**/
	private AtomicBoolean isExecute = new AtomicBoolean(true);
	
	/**
	 * 无限次定时
	 * 放到队列后 第一次执行有 intervalMill 的等待,而不是立刻执行第一次
	 * 
	 * @param intervalMill
	 *            时间间隔	
	 */
	public DistriptorTimerTask(long intervalMill) {
		this.intervalMill = intervalMill;
		// 设定执行次数
		this.count = -1;
	}
	
	
	/**
	 * 限制次数类型定时
	 * 
	 * 放到队列后 第一次执行有 intervalMill 的等待,而不是立刻执行第一次
	 * 
	 * @param intervalMill
	 *            时间间隔
	 * @param count
	 *            次数
	 */
	public DistriptorTimerTask(long intervalMill, int count) {
		this.intervalMill = intervalMill;
		// 设定执行次数
		this.count = count>0?count:1;
	}
	
	
	/**定时任务**/
	public void run()
	{
		if(!isExecute.get())
			return;
		try {
			if(count!=-1)
			{
				System.out.println(future.isCancelled());
				count--;
				if (count < 1)
					over();
			}
			isExecute.set(false);
//			long start = System.nanoTime();
			disruptorThread.put(this);
//			double userTime = (System.nanoTime() - start)/1000.0/1000.0;
//			if(userTime>10)
//			{
//				log.error(getClass().getName()+" 执行时间 :"+userTime);
//			}
		} catch (Throwable e) {
			e.printStackTrace();
		}
		
	}

	public void over() {
		if(future!=null&&!future.isCancelled())
			future.cancel(false);
	}
	
	
	
	public long getIntervalMill() {
		return intervalMill;
	}


	public void setIntervalMill(long intervalMill) {
		this.intervalMill = intervalMill;
	}


	public int getCount() {
		return count;
	}


	public ScheduledFuture<?> getFuture() {
		return future;
	}

	
	

	public void setFuture(ScheduledFuture<?> future) {
		this.future = future;
	}


	public DisruptorSingleProcessor getDisruptorThread() {
		return disruptorThread;
	}


	public void setDisruptorThread(DisruptorSingleProcessor disruptorThread) {
		this.disruptorThread = disruptorThread;
	}

	public void execute() {
		isExecute.set(true);
		onTime();
	}
	
	protected abstract void onTime();
	

	public boolean isOver()
	{
		return future.isCancelled();
	}
}
